package wechat.core;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;

/**
 * Created by CoderJiang@Sina.com on 16-6-28.
 */
public class SignatureTools {

    public static String calculateSHA1(String... params) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String[] array = params;
        StringBuffer sb = new StringBuffer();
        // 字符串排序
        Arrays.sort(array);
        int len = params.length;
        for (int i = 0; i < len; i++) {
            sb.append(array[i]);
        }

        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.reset();
        md.update(new String(sb).getBytes("UTF-8"));

        // HEX输出
        byte[] hash = md.digest();
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String hex = formatter.toString();
        formatter.close();
        return hex;
    }

}
